﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Compression;
using System.IO;

namespace CryptUtil
{
    public static class CompressUtil
    {
        /// <summary>
        /// GZIP压缩文本，返回BASE64
        /// </summary>
        /// <param name="content">原文</param>
        /// <param name="encoding">编码，默认UTF-8</param>
        /// <returns></returns>
        public static string CompressGzip(string content,Encoding encoding=null)
        {
            try
            {
                if (string.IsNullOrEmpty(content))
                    throw new Exception("内容不能为空！");
                encoding = encoding ?? Encoding.UTF8;
                byte[] conByte = encoding.GetBytes(content);
                MemoryStream ms = new MemoryStream();
                GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true);
                gzip.Write(conByte, 0, conByte.Length);
                gzip.Close();
                byte[] buffer = new byte[ms.Length] ;
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
                ms.Close();
                return Convert.ToBase64String(buffer);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// GZIP解压
        /// </summary>
        /// <param name="content">内容文本，BASE64编码</param>
        /// <param name="encoding">编码，默认UTF-8</param>
        /// <returns></returns>
        public static string DeCompressGzip(string content,Encoding encoding=null)
        {
            try
            {
                if (string.IsNullOrEmpty(content))
                    throw new Exception("内容不能为空！");
                encoding = encoding ?? Encoding.UTF8;
                byte[] conByte = Convert.FromBase64String(content);
                byte[] buffer = new byte[4096];
                //内存流存放原文
                MemoryStream ms = new MemoryStream(conByte);
                //内存流存储解压后的数据
                MemoryStream msReader = new MemoryStream();
                //GZIP流读取原文内存流
                GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress, true);
                while(true)
                {
                    //每次读4K
                    int readLength = gzip.Read(buffer, 0, buffer.Length);
                    if (readLength <= 0)
                        break;
                    //写入解压内存流
                    msReader.Write(buffer, 0, buffer.Length);
                }
                gzip.Close();
                ms.Close();
                msReader.Position = 0;
                buffer = msReader.ToArray();
                return encoding.GetString(buffer);
            }
            catch (Exception )
            {
                throw;
            }
        }
    }
}
